package com.Iconcat.system.controller;

import com.Iconcat.system.entity.CatProject;
import com.Iconcat.system.entity.CatUser;
import com.Iconcat.system.entity.Investment;
import com.Iconcat.system.response.Result;
import com.Iconcat.system.service.*;
import com.Iconcat.system.service.impl.EarningsCalculationServiceImpl;
import com.Iconcat.system.vo.WithdrawalRequestVO;
import com.Iconcat.system.vo.investProject;
import com.Iconcat.system.vo.prowithVO;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/CatProjec")
@CrossOrigin
@Api(value = "项目模块", tags = "项目接口")
public class CatProjectController {
    @Resource
    private CatProjectService catProjectService;
    @Resource
    private MovieProjectService movieProjectService;
    @Resource
    private CatUserService catUserService;
    @Resource
    private InvestmentService investmentService;
    @Resource
    private EarningsCalculationServiceImpl earningsCalculationService;
    @GetMapping("/all")
    public Result getAllProjects(
            @RequestParam(required = true, defaultValue = "1") Integer current,
            @RequestParam(required = true, defaultValue = "6") Integer size,
            @RequestParam(required = false) String searchKeyword,
            @RequestParam(required = false) Integer partitionId
    ) {
        Page<CatProject> page = new Page<>(current, size);
        LambdaQueryWrapper<CatProject> queryWrapper = new LambdaQueryWrapper<>();
        // 如果搜索关键字不为空，进行模糊查询
        if (searchKeyword != null && !searchKeyword.isEmpty()) {
            queryWrapper.like(CatProject::getProjectName, searchKeyword);
//                    .or().like(CatProject::getProj, searchKeyword);
            // 如果有其他需要查询的字段，可以继续添加 .or().like(...)
        }
        // If partitionId is provided, filter by partition ID
        if (partitionId != null) {
            queryWrapper.eq(CatProject::getPartitionId, partitionId);
        }

        // 使用 inSql 连接 cat_project_partition 表
//        if (partitionId != null) {
//            queryWrapper.inSql(CatProject::getPartitionId, "SELECT * FROM cat_project_partition WHERE partition_id = " + partitionId);
//        }

        // Perform the query
        IPage<CatProject> userPage = catProjectService.page(page, queryWrapper);
        return Result.ok().data("project", userPage);
    }

    @GetMapping("/{projectId}")
    public Result getProjectById(@PathVariable Integer projectId) {
        CatProject id = catProjectService.selectedSById(projectId);
        return Result.ok().data("project", id);
    }

    @PostMapping("/create")
    public Result createProject(@RequestBody CatProject catProject) {
        Boolean c = catProjectService.save(catProject);
        if (c) {
            return Result.ok().message("创建成功");
        } else {
            return Result.error().message("创建失败");
        }
    }

    @GetMapping("/updateIsHidden")
    public Result updateIsHidden(
            @RequestParam Integer id,
            @RequestParam Boolean isHidden
    ) {
        try {
            catProjectService.updateIsHiddenById(id, isHidden);
            return Result.ok().message("Update successful");
        } catch (Exception e) {
            return Result.error().message("Update failed");
        }
    }

    @PostMapping("/deleteUser")
    public Result deleteUser(@RequestParam Integer id) {

        Boolean P = catProjectService.deleteUserById(id);
        if (P) {
            return Result.ok().message("删除成功");
        } else {
            return Result.error().message("删除失败");
        }
    }

    @PostMapping("/updateUser")
    public Result updateUser(@RequestBody CatProject catProject) throws Exception {
        Boolean p = catProjectService.updateUserById(catProject);
        System.out.println(p);
        if (p) {
            return Result.ok().message("修改成功");
        } else {
            return Result.error().message("修改失败");
        }
    }
    @PostMapping("/invest")
    public Result investProject(
          @RequestBody investProject requestBody
    ) {
        Integer projectId=requestBody.getProjectId();
        BigDecimal investmentAmount=requestBody.getInvestmentAmount();
        Integer userId=requestBody.getUserId();
        String paymentPassword=requestBody.getPaymentPassword();
        try {
            boolean hasInvested = investmentService.hasInvested(userId, projectId);
            if (hasInvested) {
                return Result.error().message("您已经投资过该项目，无法重复投资");
            }
            // 1. 扣除用户余额
            // 假设有一个 userService 提供了扣除余额的方法
            Result deductResult=catUserService.deductBalance(userId, investmentAmount,paymentPassword);
            if (deductResult.getCode() != 200) {
                // 余额不足，返回相应错误信息
                return deductResult;
            }
            // 2. 记录投资信息
            // 假设有一个 investmentService 提供了记录投资信息的方法
            investmentService.recordInvestment(projectId, userId, investmentAmount);

            return Result.ok().message("投资成功");
        } catch (Exception e) {
            e.printStackTrace();

            return Result.error().message("扣除余额时发生异常");
        }
    }
    @PostMapping("/withdraw")
    public Result withdrawEarnings(
           @RequestBody prowithVO requestVO

    ) {
        try {
            // 获取用户的可提现收益
            CatUser user= catUserService.getById(requestVO.getUserId());
            //获取项目记录表收益
            BigDecimal Earnings=investmentService.SelectProjectEarnings(requestVO.getUserId(),requestVO.getProjectId());
            System.out.println(Earnings);
            // 将收益添加到用户余额中
            if (Earnings != null && Earnings.compareTo(BigDecimal.ZERO) > 0){
                catUserService.addBalance(requestVO.getUserId(),Earnings);
                // 更新投资信息状态为已提现
                investmentService.updateStatusToWithdrawn(requestVO.getUserId(),requestVO.getProjectId());
                catUserService.clearTotalEarnings(requestVO.getUserId());

                return Result.ok().message("提现成功");
            }
            else{
                return Result.error().message("目前没有收益");
            }
        } catch (Exception e) {
            return Result.error().message("提现失败");
        }
    }
@GetMapping("/user/earnings/{userId}/{projecId}")
public Result getUserEarnings(@PathVariable Integer userId,@PathVariable Integer projecId) {
    try {
        CatUser user = catUserService.getById(userId);

        BigDecimal ProjectEarning=investmentService.SelectProjectEarnings(userId,projecId);

        if (user != null) {
            Map<String, BigDecimal> earnings = new HashMap<>();
            earnings.put("pendingEarnings", user.getPendingEarnings());
            earnings.put("totalEarnings", user.getTotalEarnings());
            earnings.put("projectEarnings", ProjectEarning);
            return Result.ok().data("earnings", earnings);
        } else {
            return Result.error().message("用户不存在");
        }
    } catch (Exception e) {
        e.printStackTrace();
        return Result.error().message("查询失败");
    }
}

}
